package VideoPushTool.app;

import VideoPushTool.util.Configs;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;

class VideoPush implements Runnable {
    private Thread t;
    private final String threadName;

    private final int serial;

    VideoPush(String name, int n) {
        threadName = name + n;
        serial = n;
        System.out.println("Creating " + threadName);
    }

    public void run() {
        System.out.println("Running " + threadName);
        try {
            Configs.init("/test.properties");
            String serverHost = Objects.requireNonNull(Configs.get("Server.address"));
            String outputDir = Objects.requireNonNull(Configs.get("RTPGenerateOutput.dir"));

            String sim = String.format("013800138%03d", serial);

            int serverPort = Configs.getInt("Server.port", 10780);
            Socket conn = new Socket(serverHost, serverPort);
            OutputStream os = conn.getOutputStream();

            InputStream fis = Files.newInputStream(Paths.get(outputDir + sim + "-" + 1 + ".bin"));
            int len = -1;
            byte[] block = new byte[512];
            while ((len = fis.read(block)) > -1) {
                os.write(block, 0, len);
                os.flush();
                Thread.sleep(20);
            }
            os.close();
            fis.close();
            conn.close();
        } catch (InterruptedException ie) {
            System.out.println("Thread " + threadName + " interrupted.");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Thread " + threadName + " exiting.");
    }

    public void start() {
        System.out.println("Starting " + threadName);
        if (t == null) {
            t = new Thread(this, threadName);
            t.start();
        }
    }
}

public class MultiVideoPush {
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new VideoPush("Device", i).start();
        }
    }
}
